package com.ttbj.handler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ttbj.core.util.XMLUtil;

/**
 * 原生支付回调参数处理 包括app支付（微信，支付宝） 小程序支付
 * 
 * @author Medivh
 *
 */
public class NotifyHandler {

	
	/**
	 * 获取参数结果
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	public static  Map<String, String> getParamsResult(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter writer = null;
		ByteArrayOutputStream outStream = null;
		InputStream is = null;
		try {
			writer = response.getWriter();
			is = request.getInputStream();
			outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			/* xml格式的返回字符串 */
			String result = new String(outStream.toByteArray(), "UTF-8");
			Map<String, String> map = XMLUtil.doXMLParse(result);
			if (!map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
				return null;
			}
			/* 返回ok,微信后台停止回调 */
			String setXML = XMLUtil.setXML("SUCCESS", "OK");
			response.getWriter().write(setXML);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
				if (writer != null) {
					writer.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
	
	
	

}
